package net.meddeb.ppmessenger;

import net.meddeb.japptools.JApptoolsPin;

import org.apache.log4j.Logger;


public class Entrypoint {
	private final static String VERSION = "0.1.0";
	
	private static Logger logger = null;
	private static void printWelcomeMessage(){
		System.out.println("");
		System.out.println("-------------------------------------------------------------------------");
		System.out.println("ppMessenger, Password policy messenger for uDir - Version " + VERSION);
		System.out.println("Copyright (C) 2014, Abdelhamid MEDDEB (abdelhamid@meddeb.net)");
    System.out.println("This program is free software and comes with ABSOLUTELY NO WARRANTY.");
		System.out.println("-------------------------------------------------------------------------");
		System.out.println("");
	}

	public static void main(String[] args) {
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
	    public void run()
	    {
        logger.info("------------------------");
        logger.info("Shutdown of ppMessenger.");
        logger.info("------------------------");
	    }
		}));
		printWelcomeMessage();
		JNIGateway gateway = new JNIGateway();
		String params = gateway.getParams("ULDS");
		System.out.println("Params avant: " + params);
		boolean rslt = gateway.setParams("02020202","UULLLDDDSS");
		System.out.println("Change params rslt: " + rslt);
		params = gateway.getParams("ULDS");
		System.out.println("Params après: " + params);
		JApptoolsPin toolsPin = JApptoolsPin.getInstance();
		if (!toolsPin.initLog()) System.out.println("Cannot configure logging system.");
		toolsPin.initConfig();
		logger =  Logger.getLogger(Entrypoint.class);
    logger.info("");
    logger.info("-------------------");
    logger.info("ppMessenger starts.");
    logger.info("-------------------");
		Messenger messenger = new Messenger(toolsPin.getServerconf("pqParams"));
		try{
			while (true){
				logger.info("Try connection..");
				if (messenger.connect()){
					logger.info("Connected..");
					messenger.doListen();
				} else logger.info("Connection failed, wait..");
				while ((true)&&(messenger.isListening())){
					try{
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						logger.error("e: " + e.getMessage());
					}
				}
				Thread.sleep(180000); //wait 3 mn
			}
		} catch (Exception e){
			logger.error("JMS error: " + e.getMessage());
		} finally {
			logger.info("Stops the listening.");
		}
	}

}
